package com.ljx.funchat.common.event.listener;

import com.ljx.funchat.common.event.UserOnlineEvent;
import com.ljx.funchat.user.dao.UserDao;
import com.ljx.funchat.user.domain.entity.User;
import com.ljx.funchat.user.domain.enums.ChatActiveStatusEnum;
import com.ljx.funchat.user.service.cache.UserCache;
import com.ljx.funchat.user.service.cache.UserInfoCache;
import com.ljx.funchat.websocket.service.WebSocketService;
import com.ljx.funchat.websocket.service.adatper.WebSocketAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 用户上线监听器
 */
@Slf4j
@Component
public class UserOnlineListener {

    @Autowired
    private UserDao userDao;

    @Autowired
    private WebSocketService webSocketService;

    @Autowired
    private UserCache userCache;

    @Autowired
    private UserInfoCache userInfoCache;


    @Async
    @EventListener(classes = UserOnlineEvent.class)
    public void saveDB(UserOnlineEvent event) {
        User user = event.getUser();
        User update = new User();
        update.setId(user.getId());
        update.setLastOptTime(user.getLastOptTime());
        update.setIpInfo(user.getIpInfo());
        update.setActiveStatus(ChatActiveStatusEnum.ONLINE.getStatus());
        userDao.updateById(update);
    }

    @Async
    @EventListener(classes = UserOnlineEvent.class)
    public void sendMsg(UserOnlineEvent event) {
        User user = event.getUser();
        // 更新缓存
        userCache.online(user.getId(), user.getLastOptTime());
        userInfoCache.delete(user.getId());
        // 推送前端
        webSocketService.sendToAllOnline(WebSocketAdapter.buildUserOnLineResp(user));
    }

}
